# -*- coding: utf-8 -*-#

# -------------------------------------------------------------------------------
# Name:         zx
# Description:
# Author:       zx
# Date:         2021/4/1
# -------------------------------------------------------------------------------
import os

import numpy as np
import csv
from keras.models import load_model


def normailzed_maxmin(data):
    data_nor = []
    for xx in data:
        xx = np.array(xx)
        a = xx
        minval = np.min(np.where(a == 0, a.max(), a), axis=0)
        maxval = np.max(np.where(a == 0, a.min(), a), axis=0)
        max_min = maxval - minval
        for i in range(len(max_min)):
            max_min[i] = 10000 if max_min[i] == 0 else max_min[i]
        x_normed = (xx - minval) / max_min
        for i in range(len(xx)):
            for j in range(len(xx[i])):
                if xx[i][j] == 0:
                    x_normed[i][j] = 0.0
        data_nor.append(x_normed.tolist())
    return data_nor


def normailzed_meavar2(data):
    data_nor = []
    for xx in data:
        xx = np.array(xx)
        a = xx
        meaval = np.mean(a, axis=0)  # np.min(np.where(a == 0, a.max(), a), axis=0)
        varval = np.var(a, axis=0)
        for i in range(len(varval)):
            varval[i] = 1 if varval[i] == 0 else varval[i]
        x_normed = (xx - meaval) / varval
        for i in range(len(xx)):
            for j in range(len(xx[i])):
                if xx[i][j] == 0:
                    x_normed[i][j] = 0.0
        data_nor.append(x_normed.tolist())

        # exit()
    return data_nor


def predict(data):
    data = list(data)
    X = []
    b = []
    for j in range(0, 220):  # 250):
        a = []
        for i in range(1, 23):  # 25):
            try:
                if data[j][i] != '':
                    num = j
                    a.append(float(data[j][i]))
            except:
                a.append(float(data[num][i]))
            else:
                pass
        b.append(a)
    X.append(b)
    data = normailzed_maxmin(X)
    data = normailzed_meavar2(data)
    Model = load_model(os.path.dirname(os.path.abspath(__file__)) + './Convmodel.h5')
    x = Model.predict(data)
    if x > 0.5:
        x = 1
    else:
        x = 0
    # Model = load_model('./MLPmodel.h5')
    # data = np.array(data).reshape((1, 220 * 22)).tolist()
    # x = Model.predict(data)
    # print(x)
    return x
